package cn.csc.module.pay.api.order;

import cn.csc.framework.common.pojo.CommonResult;
import cn.csc.module.pay.api.order.dto.*;
import cn.csc.module.pay.controller.admin.order.vo.PayOrderSubmitReqVO;
import cn.csc.module.pay.controller.admin.order.vo.PayOrderSubmitRespVO;
import cn.csc.module.pay.convert.order.PayOrderConvert;
import cn.csc.module.pay.dal.dataobject.order.PayOrderDO;
import cn.csc.module.pay.service.jzborder.JzbOrderService;
import cn.csc.module.pay.service.order.PayOrderService;
import io.seata.core.context.RootContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.math.BigInteger;

import static cn.csc.framework.common.pojo.CommonResult.success;

/**
 * 支付单 API 实现类
 *
 * @author 
 */
@Slf4j
@RestController // 提供 RESTful API 接口，给 Feign 调用
@Validated
public class PayOrderApiImpl implements PayOrderApi {

    @Resource
    private PayOrderService payOrderService;

    @Autowired
    private JzbOrderService jzbOrderService;

    @Override
    public CommonResult<BigInteger> createOrder(PayOrderCreateReqDTO reqDTO) {
        log.info("[createOrder] 当前 XID: {}", RootContext.getXID());
        log.info("[createOrder] 参数: {}", reqDTO);
        return success(payOrderService.createPayOrder(reqDTO));
    }


    /**
     * 提交支付单
     *
     * @param reqDTO 创建请求
     * @return 支付单返回数据
     */
    @Override
    public CommonResult<PayOrderSubmitRespDTO> submitOrder(@Valid PayOrderSubmitReqDTO reqDTO) {
        PayOrderSubmitReqVO reqVO = PayOrderConvert.INSTANCE.convert(reqDTO);
        PayOrderSubmitRespVO payOrderSubmitRespVO = payOrderService.submitPayOrder(reqVO, reqDTO.getUserIp());
        return success(PayOrderConvert.INSTANCE.convert(payOrderSubmitRespVO));
    }

    @Override
    public CommonResult<PayOrderRespDTO> getOrder(BigInteger id) {
        PayOrderDO order = payOrderService.getOrder(id);
        return success(PayOrderConvert.INSTANCE.convert2(order));
    }

    /**
     * 创建分账任务
     *
     * @param reqDTO 创建分账任务参数
     * @return
     */
    @Override
    public CommonResult<Boolean> createDivide(CreateDivideReqDTO reqDTO) {
        jzbOrderService.createDivideByOrderId(reqDTO);
        return success(true);
    }


    /**
     * 创建分账任务(商户订单号+订单项ID)
     *
     * @param reqDTO 创建分账任务参数
     * @return
     */
    @Override
    public CommonResult<Boolean> createDivideByOrderItemId(@Valid CreateDivideWithOrderItemIdReqDTO reqDTO) {
        log.info("[createDivideByOrderItemId] 当前 XID: {}", RootContext.getXID());
        jzbOrderService.createDivideByOrderItemId(reqDTO);
        return success(true);
    }
}
